package com.oa.service.admin.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.oa.mapper.user.DeptMapper;
import com.oa.mapper.user.UserMapper;
import com.oa.pojo.Department;
import com.oa.pojo.Emp;
import com.oa.service.admin.DeptManagerService;
import com.oa.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: 一拳超人
 * @Date: 2021/10/18 19:21
 */
@Service
public class DeptManagerServiceImpl implements DeptManagerService {
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Department getDeptManager(Integer id) {
        Department dept = deptMapper.selectById(id);
        dept.setDepManager(userMapper.selectOne(new QueryWrapper<Emp>()
                .eq("emp_id", dept.getManagerId())).getEmpName());
        return dept;
    }

    @Override
    public List<Emp> getEmpList() {
        return userMapper.selectList(new QueryWrapper<Emp>().eq("emp_status", true));
    }

    @Override
    public Integer updateDeptInfo(Department department) {
        int i = deptMapper.updateById(department);
        return i != 0 ? 200 : 201;
    }

    @Override
    public SysResult addNewDept(Department department) {
        if (department.getManagerId() == null) {
            return SysResult.fail("查无此人");
        }
        if (department.getParentId() == null) {
            department.setParentId(0).setDepLevel(1);
        } else {
            department.setDepLevel(2);
        }
        deptMapper.insert(department);
        return SysResult.success("添加成功");
    }

    @Override
    public SysResult deleteDept(Integer depId) {
        List<Department> departmentList = deptMapper.selectList(new QueryWrapper<Department>().eq("parent_id", depId));
        if (departmentList != null && !departmentList.isEmpty()) {
            return SysResult.fail("该部门尚有下属部门,不可删除");
        } else {
            userMapper.updateDepId(depId);
            deptMapper.deleteById(depId);
            return SysResult.success("删除成功");
        }
    }
}
